<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2017/7/15
 * Time: 下午5:50
 */

namespace app\api\controller;

use Alipay\Alipayobj;
use app\common\model\Agent;
use app\common\model\DeviceMicro;
use app\common\model\Paylog;

use app\common\model\Tklog;
use app\common\model\User;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\WxOpen;
use Wechat\Wxobjopen;
use Weixinpay\Wxtk;

class HttpOrder
{
    public function paylog($data)
    {
        try {
            $Pay = new Paylog();
            $page = ($data['page'] - 1) * 10;
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);
            $map['pay_statu'] = array('in', '1,2,3');
            $map['mid'] = $data['merchid'];
            $map['add_time'] = array('between', [$start_time, $end_time]);
            $paylog = $Pay->where($map)->field('orderid,price,add_time,pay_fs,tk_price')->order('add_time desc')->limit($page, 10)->select();
            foreach ($paylog as $k => $v) {
                $paylog[$k]['refund_fee'] = $v['tk_price'];
            }

        } catch (\Exception $e) {

            $paylog = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($paylog);
    }

    //小程序交易记录
    public function paylog_micro($data)
    {
        try {
            $Pay = new Paylog();
            $Merchant = new Merchant();
            $page = ($data['page'] - 1) * 10;
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);
            $map['pay_statu'] = array('in', '1,2,3');
            $map['mid'] = $data['merchid'];

            $map['add_time'] = array('between', [$start_time, $end_time]);
            $paylog = $Pay->where($map)->field('mid,orderid,price,tk_price,add_time,pay_fs')->order('add_time desc')->limit($page, 30)->select();
            foreach ($paylog as $k => $v) {

                $paylog[$k]['refund_fee'] = $v['tk_price'];
                $paylog[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $paylog[$k]['machname'] = $Merchant->where(['id' => $v['mid']])->value('merchant');
            }

        } catch (\Exception $e) {

            $paylog = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($paylog);
    }

    public function paycount($data)
    {
        try {
            $Pay = new Paylog();
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);
            $mae['mid'] = $data['merchid'];
            $mae['add_time'] = array('between', [$start_time, $end_time]);

            $map = $mae;
            $map['pay_statu'] = 1;
            $mao = $mae;
            $mao['pay_statu'] = array('in', '2,3');
            //     return json_encode($data);
//            $pay['wx_count'] = $Pay->where($map)->where(array('pay_fs' => 0))->count();
//            $pay['wx_price'] = $Pay->where($map)->where(array('pay_fs' => 0))->sum('price');
//            $pay['ali_count'] = $Pay->where($map)->where(array('pay_fs' => 1))->count();
//            $pay['ali_price'] = $Pay->where($map)->where(array('pay_fs' => 1))->sum('price');
            //微信退款
            $pay['wx_tk_count'] = $Pay->where($mao)->where(array('pay_fs' => 2))->count();
            $pay['wx_tk_price'] = $Pay->where($mao)->where(array('pay_fs' => 2))->sum('tk_price');

            //阿里退款
            $pay['ali_tk_count'] = $Pay->where($mao)->where(array('pay_fs' => 3))->count();
            $pay['ali_tk_price'] = $Pay->where($mao)->where(array('pay_fs' => 3))->sum('tk_price');
            //微信刷卡收款
            $pay['wxcard_count'] = $Pay->where($map)->where(array('pay_fs' => 2))->count();
            $pay['wxcard_price'] = $Pay->where($map)->where(array('pay_fs' => 2))->sum('price');
            //    return $Pay->getLastSql();
            //阿里刷卡收款
            $pay['alicard_count'] = $Pay->where($map)->where(array('pay_fs' => 3))->count();
            $pay['alicard_price'] = $Pay->where($map)->where(array('pay_fs' => 3))->sum('price');
            //现金支付
            $pay['xj_count'] = $Pay->where($map)->where(array('pay_fs' => 4))->count();
            $pay['xj_price'] = $Pay->where($map)->where(array('pay_fs' => 4))->sum('price');
        } catch (\Exception $e) {
            $pay = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($pay);
    }

    public function getorderrefund($data)
    {


        try {
            if (!empty($data['orderid'])) {
                $map['orderid'] = $data['orderid'];
            } elseif (!empty($data['wsy_orderid'])) {
                $map['wsy_orderid'] = $data['wsy_orderid'];
            }

            $Paylog = new Paylog();
            $pay_fs = $Paylog->where($map)->value('pay_fs');
            if ($pay_fs) {
                $User = new Merchant();
                $shtd = $User->where(array('id' => $data['merchid']))->value('shtd');
                switch ($shtd) {
                    case '0':


                        switch ($pay_fs) {
                            case '0':
                                $arr = $this->orderrefund($data);
                                break;
                            case '1':
                                $arr = $this->aliorderrefund($data);
                                break;
                            case '2':
                                $arr = $this->orderrefund($data);
                                break;
                            case '3':
                                $arr = $this->aliorderrefund($data);
                                break;
                            case '8':
                                $arr = $this->orderrefund($data);
                                break;
                        }
                        break;

                    case '1':
                        $arr = $this->msrefund($data);
                        break;
                }
            } else {
                $arr = array('code' => '9091', 'message' => '订单编号不存在');

            }
        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($arr);
    }

    public function getorderreverse($data)
    {
        try {
            $User = new Merchant();
            $shtd = $User->where(array('id' => $data['merchid']))->value('shtd');
            switch ($shtd) {
                case '0':
                    $map['orderid'] = $data['orderid'];
                    $Paylog = new Paylog();
                    $pay_fs = $Paylog->where($map)->value('pay_fs');
                    switch ($pay_fs) {
                        case '0':
                            $arr = $this->wxreverse($data);
                            break;
                        case '1':
                            $arr = $this->alireverse($data);
                            break;
                        case '2':
                            $arr = $this->wxreverse($data);
                            break;
                        case '3':
                            $arr = $this->alireverse($data);
                            break;
                    }
                    break;
                case "1":
                    $arr = $this->msreverse($data);
            }
        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return $arr;
    }

    public function orderrefund($data)
    {
        try {
//        return $data;
            $map['id'] = $data['merchid'];
            $User = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $Patlog = new Paylog();
            $config = $User->where($map)->find();
            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            if (!empty($data['orderid'])) {
                $mab['orderid'] = $data['orderid'];
            } elseif (!empty($data['wsy_orderid'])) {
                $mab['wsy_orderid'] = $data['wsy_orderid'];
            } else {
                $mab['orderid'] = "999";
            }
            $mab['pay_statu']=array('neq',0);
            $order = $Patlog->where($mab)->find();
//        return $order;
            if ($order) {

                $options['wx_open_id'] = $agent['wx_open_id'];
                $weObj = new Wxtk($options);
                if (isset($data['wsy_tk_orderid'])) {
                    $tk_orderid = $data['wsy_tk_orderid'];
                } else {
                    $tk_orderid = $this->getorder($data['merchid']);
                }
//                return $tk_orderid;
                $notice = $weObj->generateNonceStr();
                $weObj->setParameter('appid', $users['authorizer_appid']);
                $weObj->setParameter('mch_id', $agent['partnerid']);
                $weObj->setParameter('sub_mch_id', $config['sub_mch_id']);
                $weObj->setParameter('nonce_str', $notice);
                $weObj->setParameter('refund_desc', isset($data['refund_desc']) ? $data['refund_desc'] : 0);
                $weObj->setParameter('out_trade_no', $order['orderid']);
                $weObj->setParameter('out_refund_no', $tk_orderid);
                $weObj->setParameter('total_fee', $order['price'] * 100);
                $weObj->setParameter('refund_fee', $data['refund_fee'] * 100);
                $sss = $weObj->create_refund_xml($agent['partnerkey']);
                $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
                $responseXml = $weObj->curl_post_ssl($url, $sss);
//return $sss;

                $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
                //转换成数组

                $param['orderid'] = $order['orderid'];
                $param['mid'] = $data['merchid'];
                $param['addtime'] = time();
                $param['action_user'] = isset($data['username']) ? $data['username'] : "";
                $param['tk_fs'] = "客户端退款";
                $param['pid'] = $order['id'];
                $param['refund_fee'] = $data['refund_fee'];
                $param['tk_orderid'] = $tk_orderid;
                $param['wsy_tk_orderid'] = $data['wsy_tk_orderid'];
                switch($order['pay_fs']){
                    case "2":
                        $channel="wx_barcode_pay";
                        break;
                    case "3":
                        $channel="ali_barcode_pay";

                        break;
                    default:
                        $channel="";

                }

                $responseArr = ( array )$responseObj;
                if ($responseArr['return_code'] == 'SUCCESS' && $responseArr['result_code'] == "SUCCESS") {
                    if ($responseArr['return_msg'] == 'OK') {
                        $arr = array('code' => 0, 'message' => "退款成功", 'outTradeNo' => $order['wsy_orderid'], 'out_transaction_id' => $order['orderid'], 'refundNo' => $data['wsy_tk_orderid'], 'refundFee' => $data['refund_fee'] * 100, 'channel' => $channel);
                        $param['tk_status'] = 1;
                        $param['sys_orderid'] = $responseArr['refund_id'];
                        if ($order['price'] == $order['tk_price'] + $data['refund_fee']) {
                            $sedata['pay_statu'] = 2;
                            $sedata['tk_status'] = 1;
                        } else {
                            $sedata['pay_statu'] = 3;
                            $sedata['tk_status'] = 2;
                        }
                        $sedata['tk_price'] = $order['tk_price'] + $data['refund_fee'];
                        $Patlog->save($sedata, ['orderid' => $order['orderid']]);
                    } else {
                        $arr = array('code' => 'err_code', 'message' => $responseArr['return_msg']);
                        $param['tk_status'] = 3;
                    }
                    $param['tk_info'] = json_encode($responseArr);
                    $Tklog = new Tklog();

                    $Tklog->save($param);
                } else {
                    if (isset($responseArr['err_code'])) {
                        $arr = array('code' => $responseArr['err_code'], 'message' => $responseArr['err_code_des']);
                    } else {
                        $arr = array('code' => "FAIL", 'message' => $responseArr['return_msg']);
                    }
                }

            } else {
                $arr = array('code' => "FAIL", 'message' => "订单编号不存在");

            }

        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return $arr;
    }

    public function order_refund_query($param)
    {
        try {
        if (!empty($param['orderid'])) {
            $map['orderid|orderno'] = $param['orderid'];
        } elseif (!empty($param['wsy_orderid'])) {
            $map['wsy_orderid'] = $param['wsy_orderid'];
        }
        $map['pay_statu']=array('neq',0);

        $Paylog = new Paylog();
        $pay_fs = $Paylog->where($map)->value('pay_fs');
        if ($pay_fs) {
            switch ($pay_fs) {
                case '0':
                    $arr = $this->wx_order_refund_query($param);
                    break;
                case '1':
                    $arr = $this->ali_order_refund_query($param);
                    break;
                case '2':
                    $arr = $this->wx_order_refund_query($param);
                    break;
                case '3':
                    $arr = $this->ali_order_refund_query($param);
                    break;
                case '8':
                    $arr = $this->wx_order_refund_query($param);
                    break;
            }
        } else {
            $arr = json_encode(array('code' => '9091', 'message' => '订单编号不存在'));
        }


        } catch (\Exception $e) {
            $arr = json_encode(array('code' => '9099', 'message' => '系统错误'));
        }
        return $arr;
    }

    public function wx_order_refund_query($param)
    {
        $Paylog = new Paylog();
        $mab['pay_statu']=array('neq',0);
        if (!empty($param['orderid'])) {
            $mab['orderid|orderno'] = $param['orderid'];
        } elseif (!empty($param['wsy_orderid'])) {
            $mab['wsy_orderid'] = $param['wsy_orderid'];
        }
        $id = $Paylog->where($mab)->find();

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchid'];

        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );

        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $out_trade_no = $id['orderid'];
        $out_refund_no = $param['refundNo'];
        $nonce_str = $weObj->generateNonceStr();
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $pay_xml = $weObj->createOrderrefundXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_refund_no, $out_trade_no, $nonce_str);
        $payorder_xml = $weObj->getPayRefundQuery($pay_xml);
//        return json_encode($payorder_xml);

        $sparam['return_code'] = "SUCCESS";
        if ($payorder_xml['return_code'] == "SUCCESS") {
            if ($payorder_xml['result_code'] == "SUCCESS") {
                switch($id['pay_fs']){
                    case "2":
                        $channel="wx_barcode_pay";
                        break;
                    case "3":
                        $channel="ali_barcode_pay";

                        break;
                    default:
                        $channel="";

                }
                $sparam['return_msg'] = "SUCCESS";
                $sparam['result_code'] = "SUCCESS";
                $sparam['result_msg'] = "SUCCESS";
                $sparam['outTradeNo'] = $id['wsy_orderid'];
                $sparam['channel'] = $channel;
                $sparam['out_transaction_id'] = $payorder_xml["out_trade_no"];
                $sparam['refundNo'] = $payorder_xml["out_refund_no_0"];
                $sparam['refundFee'] = $payorder_xml["refund_fee_0"];

            } else {
                $sparam['result_code'] = "FAIL";
                if (isset($payorder_xml['result_msg'])) {
                    $sparam['result_msg'] = $payorder_xml['result_msg'];
                } elseif (isset($payorder_xml['err_code'])) {
                    $sparam['result_msg'] = $payorder_xml['err_code'];
                }
            }

        } else {
            $sparam['result_code'] = "FAIL";
            if (isset($payorder_xml['result_msg'])) {
                $sparam['result_msg'] = $payorder_xml['result_msg'];
            } elseif ($payorder_xml['err_code']) {
                $sparam['result_msg'] = $payorder_xml['err_code'];
            }
        }
        return json_encode($sparam);

    }

    public function ali_order_refund_query($param)
    {
        $User = new Merchant();
        $Agent = new Agent();
        $Patlog = new Paylog();
        $users = $User->where(array('id' => $param['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $mab['pay_statu']=array('neq',0);

        if (!empty($param['orderid'])) {
            $mab['orderid|orderno'] = $param['orderid'];
        } elseif (!empty($param['wsy_orderid'])) {
            $mab['wsy_orderid'] = $param['wsy_orderid'];
        }

        $order = $Patlog->where($mab)->find();
        $Tklog = new Tklog();
        $tkorder = $Tklog->where('wsy_tk_orderid', $param['refundNo'])->value('refund_fee');
//        return $Tklog->getLastSql();
//        return $order;
        if ($order) {
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],

            );
            $aliObj = new Alipayobj($options);
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.fastpay.refund.query";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
//                'trade_no' =>"2018052821001004920505662953",
                'out_trade_no' => $order['orderid'],
                'out_request_no' => $param['refundNo'],

            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);

            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            $sparam['return_code'] = "SUCCESS";

            if ($content['alipay_trade_fastpay_refund_query_response']['code'] == "10000") {
                if (isset($content['alipay_trade_fastpay_refund_query_response']['trade_no'])) {
                    switch($order['pay_fs']){
                        case "2":
                            $channel="wx_barcode_pay";
                            break;
                        case "3":
                            $channel="ali_barcode_pay";

                            break;
                        default:
                            $channel="";

                    }
                    $sparam['return_msg'] = "SUCCESS";
                    $sparam['result_code'] = "SUCCESS";
                    $sparam['result_msg'] = "SUCCESS";
                    $sparam['outTradeNo'] = $order['wsy_orderid'];
                    $sparam['out_transaction_id'] = $order['orderid'];
                    $sparam['channel'] = $channel;
                    $sparam['refundNo'] = $param['refundNo'];
                    $sparam['refundFee'] = $content['alipay_trade_fastpay_refund_query_response']['refund_amount'] * 100;

                } else {
//                    return json_encode($content);
                    $sparam['result_code'] = "FAIL";
                    if (isset($content['alipay_trade_fastpay_refund_query_response']['sub_msg'])) {
                        $sparam['result_msg'] = $content['alipay_trade_fastpay_refund_query_response']['sub_msg'];
                    } else {
                        $sparam['result_msg'] = "查询失败";
                    }
                }
            }
            return json_encode($sparam);
        }
    }

    public function aliorderrefund($param)
    {
        try {
//            $mas['mid'] = $param['merchid'];
//            $mas['device_code'] = $param['device_code'];
//            $DeviceUser = new DeviceMicro();
//            $deviceuser = $DeviceUser->where($mas)->find();
//
//            if ($deviceuser['tk_pass'] == MD5($param['tk_pass'])) {
//                if ($deviceuser['is_tk'] == 1) {
            $User = new Merchant();
            $Agent = new Agent();
            $Patlog = new Paylog();
            $users = $User->where(array('id' => $param['merchid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            if (!empty($param['orderid'])) {
                $mab['orderid'] = $param['orderid'];
            } elseif (!empty($param['wsy_orderid'])) {
                $mab['wsy_orderid'] = $param['wsy_orderid'];
            } else {
                $mab['orderid'] = "999";
            }

            $order = $Patlog->where($mab)->find();
            if ($order) {
                $options = array(

                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],

                );

                $aliObj = new Alipayobj($options);

                $price = $param['refund_fee'];
                $sh = $param['merchid'];

                $out_trade_no = $order['orderid'];
                if (isset($param['wsy_tk_orderid'])) {
                    $out_request_no = $param['wsy_tk_orderid'];
                } else {
                    $out_request_no = $this->getorder($param['merchid']);
                }
                $total_fee = $price;
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.trade.refund";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
                    'out_trade_no' => $out_trade_no,
                    'refund_amount' => $total_fee,
                    'refund_reason' => isset($data['refund_desc']) ? $data['refund_desc'] : 0,
                    'out_request_no' => $out_request_no,
                    'operator_id' => isset($param['username']) ? $param['username'] : "",
                    'alipay_store_id' => $users['ali_store_id'],

                ));

//                return $data;
                $params['orderid'] = $order['orderid'];
                $params['mid'] = $param['merchid'];
                $params['addtime'] = time();
                $params['action_user'] = isset($param['username']) ? $param['username'] : "";
                $params['tk_fs'] = "客户端退款";
                $params['pid'] = $order['id'];
                $params['refund_fee'] = $param['refund_fee'];
                $params['tk_orderid'] = $out_request_no;
                $params['wsy_tk_orderid'] = $param['wsy_tk_orderid'];
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);
                switch($order['pay_fs']){
                    case "2":
                        $channel="wx_barcode_pay";
                        break;
                    case "3":
                        $channel="ali_barcode_pay";

                        break;
                    default:
                        $channel="";

                }
                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

                if ($content['alipay_trade_refund_response']['code'] == 10000) {
                    if ($content['alipay_trade_refund_response']['msg'] == "Success") {
                        $arr = array('code' => 0, 'message' => "退款成功", 'outTradeNo' => $order['wsy_orderid'], 'out_transaction_id' => $order['orderid'], 'refundNo' => $params['wsy_tk_orderid'], 'refundFee' => $param['refund_fee'] * 100, 'channel' => $channel);
                        if ($order['price'] == $order['tk_price'] + $param['refund_fee']) {
                            $sedata['pay_statu'] = 2;
                            $sedata['tk_status'] = 1;
                        } else {
                            $sedata['pay_statu'] = 3;
                            $sedata['tk_status'] = 2;
                        }
                        $sedata['tk_price'] = $order['tk_price'] + $param['refund_fee'];
                        $Patlog->save($sedata, ['orderid' => $param['orderid']]);
//                        $param['sys_orderid'] = $content['alipay_trade_refund_response']['trade_no'];
                        $params['tk_status'] = 1;
                    } else {
                        $arr = array('code' => $content['alipay_trade_refund_response']['sub_code'], 'message' => $content['alipay_trade_refund_response']['sub_msg']);
                        $params['tk_status'] = 3;
                    }
                } else {
                    $arr = array('code' => $content['alipay_trade_refund_response']['sub_code'], 'message' => $content['alipay_trade_refund_response']['sub_msg']);
                }
                $params['tk_info'] = json_encode($content);
                $Tklog = new Tklog();

                $Tklog->save($params);
            } else {
                $arr = array('code' => "FAIL", 'message' => "订单编号不存在");

            }
//                } else {
//                    $arr = array('code' => 80002, 'message' => '该登录账户没有退款权限');
//                }
//            } else {
//                $arr = array('code' => 80001, 'message' => '退款密码错误');
//            }

        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }

        return $arr;
    }

    public function wxreverse($data)
    {
//        $data['merchid']=602;
//        $data['orderid']='123';
        try {
            $map['id'] = $data['merchid'];
            $User = new Merchant();
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $config = $User->where($map)->find();

            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
            $options['wx_open_id'] = $agent['wx_open_id'];
            $weObj = new Wxtk($options);
            $notice = $weObj->generateNonceStr();
            $weObj->setParameter('appid', $users['authorizer_appid']);
            $weObj->setParameter('mch_id', $agent['partnerid']);
            $weObj->setParameter('sub_mch_id', $config['sub_mch_id']);
            $weObj->setParameter('nonce_str', $notice);
            $weObj->setParameter('out_trade_no', $data['orderid']);
            $sss = $weObj->create_refund_xml($agent['partnerkey']);
            $url = 'https://api.mch.weixin.qq.com/secapi/pay/reverse';
            $responseXml = $weObj->curl_post_ssl($url, $sss);
            $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
            $responseArr = ( array )$responseObj;
            if ($responseArr['return_code'] == "SUCCESS" && $responseArr['result_code'] = "SUCCESS") {
                $arr = array('code' => 0, 'message' => "订单已撤销");
                $sdata['pay_statu'] = 8;
                $Paylog = new Paylog();
                $Paylog->save($sdata, ['orderid' => $data['orderid']]);

            } else {
                $arr = array('code' => 80010, 'message' => "订单无法撤销");
            }

        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($arr);
    }

    public function alireverse($param)
    {
        try {

            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $param['merchid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(

                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],

            );

            $aliObj = new Alipayobj($options);
            $out_trade_no = $param['orderid'];
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.cancel";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'out_trade_no' => $out_trade_no,

            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);

            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            if ($content['alipay_trade_cancel_response']['code'] == 10000) {
                if ($content['alipay_trade_cancel_response']['msg'] == "Success") {
                    $arr = array('code' => 0, 'message' => "订单已撤销");
                    $sdata['pay_statu'] = 8;
                    $Paylog = new Paylog();
                    $Paylog->save($sdata, ['orderid' => $param['orderid']]);
                } else {
                    $arr = array('code' => 80010, 'message' => "订单无法撤销");
                }
            } else {
                $arr = array('code' => 80011, 'message' => "订单无法撤销");
            }
        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($arr);
    }

    public function msrefund($data)
    {
        try {
            $mas['mid'] = $data['merchid'];
//            $mas['username'] = $data['username'];
            $mas['device_code'] = $data['device_code'];
            $DeviceUser = new DeviceMicro();
            $deviceuser = $DeviceUser->where($mas)->find();

            if ($deviceuser['tk_pass'] == MD5($data['tk_pass'])) {
                if ($deviceuser['is_tk'] == 1) {

                    $map['id'] = $data['merchid'];
                    $User = new Merchant();
                    $Agent = new Agent();
                    $Paylog = new Paylog();
                    $config = $User->where($map)->find();
                    $agent = $Agent->where(array('id' => $config['agent']))->find();
                    $order = $Paylog->where('ms_orderid', $data['orderid'])->find();
                    $options = array(
                        'cmmb_key' => $agent['cmmb_key'],
                    );
                    $weObj = new Wxobjopen($options);
                    $out_request_no = $this->getorder($data['merchid']);
                    $param['merNo'] = $config['cmmb_mer_id'];
                    $param['money'] = 0.01 * 100;
                    $param['orgTransId'] = $data['orderid'];
                    $param['reqId'] = $out_request_no;
                    $param['reqTime'] = date('YmdHis');
                    $param['signIn'] = $weObj->getcmmbpaysignature($param);
                    $sj = $weObj->cmmbpaytk($param);
                    $sj = json_decode($sj, true);
                    $params['orderid'] = $order['orderid'];
                    $params['ms_orderid'] = $data['orderid'];
                    $params['mid'] = $data['merchid'];
                    $params['addtime'] = time();
                    $params['action_user'] = $data['username'];
                    $params['tk_fs'] = "客户端退款";
                    $params['pid'] = $order['id'];
                    $params['refund_fee'] = $data['refund_fee'];
                    $params['tk_orderid'] = $out_request_no;
                    if ($sj['result'] == "0000") {
                        if ($order['price'] == $order['tk_price'] + $data['refund_fee']) {
                            $sedata['pay_statu'] = 2;
                            $sedata['tk_status'] = 1;
                        } else {
                            $sedata['pay_statu'] = 3;
                            $sedata['tk_status'] = 2;
                        }
                        $sedata['tk_price'] = $order['tk_price'] + $data['refund_fee'];
                        $Paylog->save($sedata, ['ms_orderid' => $data['orderid']]);
                        $arr = array('code' => 'err_code', 'message' => "退款成功");
                        $params['tk_status'] = 1;
                    } else {
                        $arr = array('code' => $sj['result'], 'message' => $sj['desc']);
                        $params['tk_status'] = 3;
                    }

                    $params['tk_info'] = json_encode($sj);
                    $Tklog = new Tklog();

                    $Tklog->save($params);
                } else {
                    $arr = array('code' => 80002, 'message' => '该登录账户没有退款权限');
                }
            } else {
                $arr = array('code' => 80001, 'message' => '退款密码错误');
            }
        } catch (\Exception $e) {
            $arr = array('code' => '9099', 'message' => '系统错误');
        }
        return json_encode($arr);
    }

    public function msreverse($param)
    {

        $map['id'] = $param['merchid'];
        $User = new Merchant();
        $Agent = new Agent();
        $config = $User->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $options = array(
            'cmmb_key' => $agent['cmmb_key'],
        );
        $weObj = new Wxobjopen($options);
        $params['merNo'] = $config['cmmb_mer_id'];
        $params['orderNo'] = $param['orderid'];
        $params['reqId'] = $this->getorder2($param['merchid']);
        $params['reqTime'] = date('YmdHis');
        $params['signIn'] = $weObj->getcmmbpaysignature($params);
        $sj = $weObj->cmmbpayreverse($params);
        $sj = json_decode($sj, true);
        if ($sj['result'] == "0000") {

            $arr = array('code' => 0, 'message' => "订单撤销成功");
            $sdata['pay_statu'] = 8;
            $Paylog = new Paylog();
            $Paylog->save($sdata, ['orderid' => $param['orderid']]);

        } elseif ($sj['result'] == "0033" || $sj['result'] == "0042") {
            $ss = $this->msorderclose($param);
            if ($ss == 0) {
                $arr = array('code' => 0, 'message' => "订单撤销成功");
                $sdata['pay_statu'] = 9;
                $Paylog = new Paylog();
                $Paylog->save($sdata, ['orderid' => $param['orderid']]);
            } else {
                $arr = array('code' => 80011, 'message' => $ss);
            }
        } else {
            $arr = array('code' => 80011, 'message' => $sj['desc']);
        }

        return json_encode($arr, JSON_UNESCAPED_UNICODE);

    }

    public function msorderclose($param)
    {

        $map['id'] = $param['merchid'];
        $User = new Merchant();
        $Agent = new Agent();
        $config = $User->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $options = array(
            'cmmb_key' => $agent['cmmb_key'],
        );
        $weObj = new Wxobjopen($options);
        $params['merNo'] = $config['cmmb_mer_id'];
        $params['orderNo'] = $param['orderid'];
        $params['signIn'] = $weObj->getcmmbpaysignature($params);
//        return $params;
        $sj = $weObj->cmmb_order_close($params);

        $sj = json_decode($sj, true);
        if ($sj['result'] == "0000") {
            $code = 0;
        } else {
            $code = $sj['result'];
        }
        return $code;
    }

    public function getorderprice($data)
    {


        $map['mid'] = $data['merchid'];
        $User = new Merchant();
        $shtd = $User->where('id', $data['merchid'])->value('shtd');
        if ($shtd == 0) {
            $map['orderid'] = $data['orderid'];
        } elseif ($shtd == 1) {
            $map['ms_orderid'] = $data['orderid'];
        }
        $Paylog = new Paylog();
        $order = $Paylog->where($map)->find();
//        $addtime=;
        $Tklog = new Tklog();
        $map['tk_status'] = 1;
        $map['orderid'] = $order['orderid'];
        $ytk = $Tklog->where($map)->sum('refund_fee');
        if ($order) {
            $arr = array('orderid' => $order['orderid'], 'pay_fs' => $order['pay_fs'], 'price' => $order['price'], 'refund_fee' => $ytk, 't_orderid' => $order['orderid'], 'orderno' => $order['orderno'], 'cashier' => $order['d_cashier'], 'add_time' => date('YmdHis', $order['add_time']), 'openid' => $order['openid']);
        } else {
            $arr = array('code' => '40010', 'message' => "订单编号不存在");
        }
        return json_encode($arr);


    }

    private function getorder($sh)
    {

        $order = "H" . $sh  . date('YmdHis') . rand(10000, 99999) . rand(1, 9) . "_tk";
        return $order;

    }

    private function getorder2($sh)
    {

        $order = "H" . $sh . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        return $order;

    }
}